package com.neuedu.shop.service.impl;

import com.neuedu.shop.entity.Category;
import com.neuedu.shop.entity.Product;
import com.neuedu.shop.mapper.CategoryMapper;
import com.neuedu.shop.mapper.ProductMapper;
import com.neuedu.shop.service.ProductService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.neuedu.shop.util.CommonUtil;
import com.neuedu.shop.vo.ConditionVO;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Qin
 * @since 2021-04-10
 */
@Service
@Transactional
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {
    @Resource
    private ProductMapper mapper;
    @Resource
    private CategoryMapper categoryMapper;
    @Override
    public List<Product> selectAll() {
        return mapper.selectAll();
    }

    @Override
    public List<Category> findTheThirdGrade() {
        return categoryMapper.findTheThirdGrade();
    }

    @Override
    public void insertProduct(Product product, CommonsMultipartFile file, HttpServletRequest request) {
        //上传到服务器
        String path=request.getServletContext().getRealPath("/")+"/images/"+
                UUID.randomUUID().toString().replace("-","")+
                //扩展名
                file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        File f = new File(path);
        File fileParent = f.getParentFile();
        if (!fileParent.exists()){
            fileParent.mkdir();
        }

        try {
            file.transferTo(f);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //将图片路径存到数据库
        String imgPath = "/images" + path.substring(path.lastIndexOf("/"));
        product.setProductImgpath(imgPath);
        mapper.insertProduct(product);

        //拷贝到本地
        CommonUtil.fileCopyToLocation(path,
                CommonUtil.IMG_PATH + imgPath);
    }

    @Override
    public List<Product> complexSearchByCondition(ConditionVO vo) {
        return mapper.complexSearchByCondition(vo);
    }
}
